package com.tz;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by sztzedu on 16-10-10.
 */
@Configuration
@ComponentScan({"com.tz.dao", "com.tz.service"})
@EnableAspectJAutoProxy //启用aop
@EnableTransactionManagement //启用DT
public class AppConfig {

    //数据源
    @Bean
    public DataSource dataSource() {
        //实例化数据源
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
        dataSource.setUsername("jsd1606");
        dataSource.setPassword("jsd1606");
        //连接数
        dataSource.setInitialSize(5);
        return dataSource;
    }

    //session 工厂
    @Bean
    public LocalSessionFactoryBean sessionFactory(){
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        //1.数据源
        lsfb.setDataSource(this.dataSource());
        //2.方言等属性
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        props.setProperty("hibernate.show_sql", "true");
        lsfb.setHibernateProperties(props);
        //3.注册ORM信息
        lsfb.setPackagesToScan("com.tz.entity");
        return lsfb;
    }

    //事务管理器
    @Bean
    public HibernateTransactionManager tm(){
        HibernateTransactionManager tm = new HibernateTransactionManager();
        tm.setSessionFactory(sessionFactory().getObject()); //手动解封装
        return tm;
    }

}
